package com.aijk.web.admin.controller.openapi;

import com.aijk.commons.mijo.utils.PojoUtil;
import com.aijk.commons.utils.PasswordHelper;
import com.aijk.commons.utils.Utils;
import com.aijk.ehm.api.*;
import com.aijk.ehm.captcha.api.CaptchaApi;
import com.aijk.ehm.captcha.entity.CaptchaCheckReq;
import com.aijk.ehm.captcha.entity.CaptchaCheckRes;
import com.aijk.ehm.model.EhmCompany;
import com.aijk.ehm.model.EhmPeopleCrowd;
import com.aijk.ehm.model.EhmResident;
import com.aijk.ehm.model.EhmResidentCrowd;
import com.aijk.ehm.model.dto.EhmResidentCrowdDto;
import com.aijk.ehm.model.qo.EhmPeopleCrowdQo;
import com.aijk.ehm.model.qo.EhmResidentCrowdQo;
import com.aijk.ehm.model.qo.EhmResidentQo;
import com.aijk.ehm.model.vo.BasUserVo;
import com.aijk.ehm.model.vo.EhmResidentVo;
import com.aijk.web.admin.config.Constant;
import com.aijk.web.admin.config.JobStatus;
import com.aijk.web.admin.config.Status;
import com.aijk.web.admin.controller.openapi.entity.ApiResponse;
import com.aijk.web.admin.entity.ResidentCrowdExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.*;

@Component
@Controller
public class EhmResidentController extends ApiBaseController {

    private static final Logger logger = LoggerFactory.getLogger(EhmResidentController.class);

    @Autowired
    private EhmResidentApi residentApi;
    @Autowired
    private EhmResidentCrowdApi residentCrowdApi;
    @Autowired
    private EhmPeopleCrowdApi crowdApi;
    @Autowired
    private EhmCompanyApi companyApi;
    @Autowired
    private CaptchaApi captchaApi;

    @Autowired
    private EhmResidentCrowdApi ehmResidentCrowdApi;

    @Autowired
    private EhmPeopleCrowdApi ehmPeopleCrowdApi;

    @Autowired
    private BasUserApi basUserApi;

    /**
     *  获取用户信息
     * @return
     */
    @RequestMapping(path = "app/resident/info", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object info(@RequestParam Long companyId ,@RequestParam Long id ,@RequestParam Long uid) {
      /*  if(StringUtils.isEmpty(checkReq.getCaptcha())||StringUtils.isEmpty(checkReq.getKey()))
            return  new ApiResponse("-1","参数异常");*/
        EhmResidentQo residentQo = new EhmResidentQo();
        List<Short> Jstatus = new ArrayList<>();
        Jstatus.add(JobStatus.OFFLINE.getStatus());
        Jstatus.add(JobStatus.OFFLINE.getStatus());
        if(StringUtils.isEmpty(residentQo.getJstatus())) residentQo.setJstatusIn(Jstatus);
//        BeanUtils.copyProperties(residentQo,resident);
        residentQo.setId(id);
        residentQo.setUid(uid);
        residentQo.setCompanyId(companyId);
        List<EhmResidentVo> residentVos = residentApi.list(residentQo);
        if (residentVos.size() <0) return new ApiResponse("-1","用户不存在");

        //获取人群信息
        ResidentCrowdExt residentCrowdExt = PojoUtil.convert(residentVos.get(0), ResidentCrowdExt.class);
        List<EhmResidentCrowd> rsdtCowds = residentCrowdApi.list(new EhmResidentCrowdQo(residentVos.get(0).getId(),residentVos.get(0).getUid()));
        if (rsdtCowds.size() >0){
            String rids ="";
            String cname="";
            if(null!=rsdtCowds){
                for (EhmResidentCrowd ehmResidentCrowd : rsdtCowds){
                    EhmPeopleCrowd crowd = ehmPeopleCrowdApi.findOne(ehmResidentCrowd.getCrowdId());
                    if(crowd!=null){
                        rids+=ehmResidentCrowd.getCrowdId()+",";
                        cname+=crowd.getTitle()+",";
                    }
                }
            }
            if(rids.length()>0){
                residentCrowdExt.setCrowd(rids.substring(0, rids.length() - 1));
            }
            if(cname.length()>0){
                residentCrowdExt.setCrowdname( cname.substring(0, cname.length() - 1));
            }
        }


        ApiResponse response =  new ApiResponse();
        response.setData(residentCrowdExt);
        return response;
    }

    /**
     *  获取用户信息
     * @return
     */
    @RequestMapping(path = "app/resident/get", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object get(@RequestParam Long companyId ,@RequestParam String workno) {
        EhmResidentQo residentQo = new EhmResidentQo();
        List<Short> Jstatus = new ArrayList<>();
        Jstatus.add(JobStatus.OFFLINE.getStatus());
        Jstatus.add(JobStatus.OFFLINE.getStatus());
        if(StringUtils.isEmpty(residentQo.getJstatus())) residentQo.setJstatusIn(Jstatus);
        residentQo.setWorkno(workno);
        residentQo.setCompanyId(companyId);
        List<EhmResidentVo> residentVos = residentApi.list(residentQo);
        if (residentVos == null || residentVos.size() ==0) return new ApiResponse("-1","用户不存在");

        ResidentCrowdExt residentCrowdExt = PojoUtil.convert(residentVos.get(0), ResidentCrowdExt.class);
        ApiResponse response =  new ApiResponse();
        response.setData(residentCrowdExt);
        return response;
    }


    /**
     *  更改用户信息
     * @param resident
     * @return
     */
    @RequestMapping(path = "app/resident/update", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object infoupdate(@Valid EhmResident resident) {
        if(StringUtils.isEmpty(resident.getId()))
            return  new ApiResponse("-1","参数异常");

        EhmResident rmode = residentApi.findOne(resident.getId());

        if(resident.getCrowd()!=null && resident.getCrowd()!=""){
            String[] crow = resident.getCrowd().split(",");

            EhmResidentCrowdQo qo = new EhmResidentCrowdQo();
            qo.setResidentId(resident.getId());
            List<EhmResidentCrowd> ehmResidentCrowdList = ehmResidentCrowdApi.list(qo);
            if(crow != null && crow.length > 0){
                if(ehmResidentCrowdList!=null && ehmResidentCrowdList.size() > 0){
                    EhmResidentCrowdQo deleteQo = new EhmResidentCrowdQo();
                    deleteQo.setResidentId(resident.getId());
                    deleteQo.setUid(rmode.getUid());
                    ehmResidentCrowdApi.deleteQo(deleteQo);
                }
                for (String str : crow){
                    EhmResidentCrowd ehmResidentCrowd = new EhmResidentCrowd();
                    ehmResidentCrowd.setResidentId(resident.getId());
                    ehmResidentCrowd.setUid(rmode.getUid());
                    ehmResidentCrowd.setCrowdId(Utils.toLong(str));
                    ehmResidentCrowd.setCreated(new Date());
                    ehmResidentCrowd.setModified(new Date());
                    ehmResidentCrowdApi.save(ehmResidentCrowd);
                }

            }
        }

//        resident.setCrowd("");
        residentApi.update(resident);
        return new ApiResponse("0","修改成功");
    }

    /**
     * 忘记密码
     * @param checkReq
     * @param password
     * @param residentId
     * @return
     */
    @RequestMapping(path = "app/resident/pwd/find", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pwdFind(@Valid CaptchaCheckReq checkReq, @RequestParam(name = "password",required = true) String password,@RequestParam(name = "residentId",required = true) Long residentId) {
        if(StringUtils.isEmpty(checkReq.getCaptcha())||StringUtils.isEmpty(checkReq.getKey()))
            return  new ApiResponse("-1","参数异常");
        EhmResidentVo resident = residentApi.findOne(residentId);
        if (resident == null) return new ApiResponse("-1","用户不存在");
        checkReq.setKey(Constant.CAPTCHA_KEY+checkReq.getKey());
        CaptchaCheckRes checkRes = captchaApi.check(checkReq);
        if(checkRes.getSuccess()!=CaptchaCheckRes.RESULT_SUCCESS)return new ApiResponse("-1","验证码错误");
        EhmResident updateResident =new EhmResident();
        BeanUtils.copyProperties(resident,updateResident);
        updateResident.setPassword(PasswordHelper.encryptPassword(password,resident.getSalt()));
        if(residentApi.update(updateResident)>0) return new ApiResponse();
        return  new ApiResponse("-1","找回失败!请重试");
    }


    /**
     * 绑定手机号
     * @param checkReq
     * @param mobile
     * @param residentId
     * @return
     */
    @RequestMapping(path = "app/resident/bind/mobile", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object bindMobile(@Valid CaptchaCheckReq checkReq, @RequestParam(name = "mobile",required = true) String mobile,@RequestParam(name = "residentId",required = true) Long residentId) {
        if(StringUtils.isEmpty(checkReq.getCaptcha())||StringUtils.isEmpty(checkReq.getKey()))
            return  new ApiResponse("-1","参数异常");
        EhmResidentVo resident = residentApi.findOne(residentId);
        if (resident == null) return new ApiResponse("-1","用户不存在");
        checkReq.setKey(Constant.CAPTCHA_KEY+checkReq.getKey());
        CaptchaCheckRes checkRes = captchaApi.check(checkReq);
        if(checkRes.getSuccess()!=CaptchaCheckRes.RESULT_SUCCESS)return new ApiResponse("-1","验证码错误");
//        EhmResident updateResident =new EhmResident();
//        BeanUtils.copyProperties(updateResident,resident);
        resident.setCellphone(mobile);
        resident.setAppStatus((short)1);
        if(residentApi.update(resident) > 0)
            return new ApiResponse();

        return  new ApiResponse("-1","绑定失败、请重试");
    }

    /**
     * 个人中心
     * @param resident  {id}
     * @return
     */
        @RequestMapping(path = "app/resident/center", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object center(@Valid EhmResident resident) {
        if(StringUtils.isEmpty(resident.getId()))
            return  new ApiResponse("-1","参数异常");
        Map<String,Object> retMap =new HashMap<>();
        EhmResident exitedResident = residentApi.findOne(resident.getId());
        BasUserVo basUserVo = basUserApi.findOne(exitedResident.getUid());
        exitedResident.setIdcard(basUserVo.getIdcard());
        retMap.put("resident",exitedResident); //包含企业信息
        /*获取人群信息*/
        List<EhmPeopleCrowd> crowds = crowdApi.list(new EhmPeopleCrowdQo());
        Map<Long,EhmPeopleCrowd> crowdMap = new HashMap<>();
        for (EhmPeopleCrowd crowd:crowds){
            crowdMap.put(crowd.getId(),crowd);
        }
        List<EhmResidentCrowd> rsdtCowds = residentCrowdApi.list(new EhmResidentCrowdQo(exitedResident.getId(),exitedResident.getUid()));
        List<EhmPeopleCrowd>  rsdtCowdList = new ArrayList<>();
        for (EhmResidentCrowd crowd : rsdtCowds){
            if(crowdMap.containsKey(crowd.getCrowdId()))rsdtCowdList.add(crowdMap.get(crowd.getCrowdId()));
        }
        retMap.put("crowds",rsdtCowdList);
    /*    EhmCompany company = companyApi.findOne(resident.getCompanyId());
        retMap.put("company",company);*/



        ApiResponse response =  new ApiResponse();
        response.setData(retMap);
        return response;
    }

    /**
     * 员工登录
     * @param resident  {companyId、password、workno}
     * @return
     */
    @RequestMapping(path = "app/resident/logon", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object logon(@Valid EhmResident resident) {
        if(StringUtils.isEmpty(resident.getCompanyId())||StringUtils.isEmpty(resident.getPassword())||StringUtils.isEmpty(resident.getWorkno()))
            return  new ApiResponse("-1","参数异常");
        //PasswordHelper.encryptPassword()
        EhmResidentQo residentQo =new EhmResidentQo();
        residentQo.setCompanyId(resident.getCompanyId());
        residentQo.setWorkno(resident.getWorkno());
        List<EhmResidentVo> residents = residentApi.list(residentQo);
        if(residents.size()<=0) return  new ApiResponse("-1","企业和工号不符");
        EhmResident exitedResident = residents.get(0);
        if(!exitedResident.getPassword().equals(PasswordHelper.encryptPassword(resident.getPassword(),exitedResident.getSalt())))
            return  new ApiResponse("-1","密码错误");

        if(exitedResident.getJstatus().equals(JobStatus.LEAVE.getStatus()))
            return  new ApiResponse("-1","您的工号已失效");

        Integer status = exitedResident.getStatus() & 0xff;
        if(status == 20)
            return  new ApiResponse("-1","您的工号已禁用");

        EhmCompany company = companyApi.findOne(resident.getCompanyId());
        if(company==null||company.getStatus().equals(Status.DISABLE))  return  new ApiResponse("-1","企业无效");

        //获取人群信息
        ResidentCrowdExt residentCrowdExt = PojoUtil.convert(exitedResident, ResidentCrowdExt.class);
        List<EhmResidentCrowd> rsdtCowds = residentCrowdApi.list(new EhmResidentCrowdQo(exitedResident.getId(),exitedResident.getUid()));
        if (rsdtCowds.size() >0){
            String rids ="";
            String cname="";
            if(null!=rsdtCowds){
                for (EhmResidentCrowd ehmResidentCrowd : rsdtCowds){
                    EhmPeopleCrowd crowd = ehmPeopleCrowdApi.findOne(ehmResidentCrowd.getCrowdId());
                    if(null!=crowd){
                        rids+=ehmResidentCrowd.getCrowdId()+",";
                        cname+=crowd.getTitle()+",";
                    }
                }
            }
            if(rids.length()>0){
                residentCrowdExt.setCrowd(rids.substring(0, rids.length() - 1));
            }
            if(cname.length()>0){
                residentCrowdExt.setCrowdname(cname.substring(0, cname.length() - 1));
            }
        }

        BasUserVo basUserVo = basUserApi.findOne(residentCrowdExt.getUid());
        residentCrowdExt.setIdcard(basUserVo.getIdcard());
        ApiResponse response =  new ApiResponse();
        response.setData(residentCrowdExt);
        return response;
    }

    /**
     * 设置居民人群类型
     * @param residentCrowdDto  {uid,residentId,crowdIds <1,2>}
     * @return
     */
    @RequestMapping(path = "app/resident/crowd/set", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object crowdSet(@Valid EhmResidentCrowdDto residentCrowdDto) {
        if(StringUtils.isEmpty(residentCrowdDto.getUid())||StringUtils.isEmpty(residentCrowdDto.getResidentId())||StringUtils.isEmpty(residentCrowdDto.getCrowdIds()))
            return  new ApiResponse("-1","参数异常");

        EhmResidentCrowdQo residentCrowdQo = new EhmResidentCrowdQo();
        residentCrowdQo.setUid(residentCrowdDto.getUid());
        residentCrowdQo.setResidentId(residentCrowdDto.getResidentId());
        List<EhmResidentCrowd> crowds = residentCrowdApi.list(residentCrowdQo);
        if(crowds.size()>0){
            return  new ApiResponse("-1","请勿重复设置!");
        }
        for(Long crowdId:residentCrowdDto.getCrowdIds()){
            EhmResidentCrowd residentCrowd = new EhmResidentCrowd();
            residentCrowd.setUid(residentCrowdDto.getUid());
            residentCrowd.setResidentId(residentCrowdDto.getResidentId());
            residentCrowd.setCrowdId(crowdId);
            residentCrowd.setCreated(new Date());
            residentCrowdApi.save(residentCrowd);
        }
        return new ApiResponse();
    }


}
